package kr.hkit.powerjava.chapter23;

class Counter{
	private int value = 0;
	public synchronized void increment() { value++; }
	public synchronized void decrement() { value--; }
	public synchronized void prnCounter() { System.out.println(value); }
}

class SharedThread extends Thread {
	Counter sharedCounter;
	public SharedThread(Counter sharedCounter) {
		this.sharedCounter = sharedCounter;
		start();
	}
	
	@Override
	public void run() {
		int i = 0;
		while(i < 20000) {
			sharedCounter.increment();	//csount에 있는 value값을 1씩 증가
			sharedCounter.decrement();	//count에 있는 value값을 1씩 감소
			
			if(i % 40 == 0) 
				sharedCounter.prnCounter();
			
			try {
				sleep((int)Math.random() * 2);
			} catch(InterruptedException e) {}
			
			i++;
			
		}
	}
}


public class CounterTest {
	
	public static void main(String[] args) {
		Counter c = new Counter();
		
		new SharedThread(c);
		new SharedThread(c);
		new SharedThread(c);
		new SharedThread(c);
		
		//각 각 쓰레드가 c를 공유함.
		
		
	}
	
	
}